<?php


namespace Home\Controller;

use Think\Controller;

/**
 * 登录验证过滤器
 */
class BaseController extends Controller
{
    public function _initialize()
    {
        //处理自动登录
        if (isset($_COOKIE['auto']) && !isset($_SESSION['uid'])) {
            $value = explode('|', encryption($_COOKIE['auto'], 1));
            $ip = get_client_ip();
            //本次登录IP与上一次登录IP一致时
            if ($ip == $value[1]) {
                $account = $value[0];
                $where = array('account' => $account);
                $user = M('user')->where($where)->field(array('id', 'lock'))->find();
                //检索出用户信息并且该用户没有被锁定时，保存登录状态
                if ($user && !$user['lock']) {
                    session('uid', $user['id']);
                }
            }
        }
        if (!isset($_SESSION['uid'])) {
            redirect(U('Login/index', '', ''));
        }
    }

    /**
     * 头像上传
     */
    public function uploadFace()
    {
        $upload = $this->_upload('Face', '160,480,800', '160,480,800');
        echo json_encode($upload);
    }

    /**
     * 微博图片上传
     */
    public function uploadPic()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }
        $upload = $this->_upload('Pic', '120,360,540', '120,360,540');
        echo json_encode($upload);
    }

    /**
     * 异步创建新分组
     */
    public function addGroup()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }
        $data = array(
            'name' => I('post.name'),
            'uid' => session('uid')
        );
        if (M('group')->data($data)->add()) {
            echo json_encode(array('status' => 1, 'msg' => '创建成功'));
        } else {
            echo json_encode(array('status' => 0, 'msg' => '创建失败,请重试...'));
        }
    }

    /**
     * 异步添加关注
     */
    public function addFollow()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }
        $data = array(
            'follow' => I('post.follow', 'intval'),
            'fans' => (int)session('uid'),
            'gid' => I('post.gid', 'intval')
        );
        if (M('follow')->data($data)->add()) {
            $db = M('userinfo');
            $db->where(array('uid' => $data['follow']))->setInc('fans');
            $db->where(array('uid' => session('uid')))->setInc('follow');
            echo json_encode(array('status' => 1, 'msg' => '关注成功'));
        } else {
            echo json_encode(array('status' => 0, 'msg' => '关注失败请重试...'));
        }
    }

    /**
     * 异步移除关注与粉丝
     */
    public function delFollow()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }

        $uid = I('post.uid', 'intval');
        $type = I('post.type', 'intval');

        $where = $type ? array('follow' => $uid, 'fans' => session('uid')) : array('fans' => $uid, 'follow' => session('uid'));

        if (M('follow')->where($where)->delete()) {
            $db = M('userinfo');

            if ($type) {
                $db->where(array('uid' => session('uid')))->setDec('follow');
                $db->where(array('uid' => $uid))->setDec('fans');
            } else {
                $db->where(array('uid' => session('uid')))->setDec('fans');
                $db->where(array('uid' => $uid))->setDec('follow');
            }

            echo 1;
        } else {
            echo 0;
        }
    }

    /**
     * 异步修改模版风格
     */
    public function editStyle()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }

        $style = I('post.style');
        $where = array('uid' => session('uid'));

        if (M('userinfo')->where($where)->save(array('style' => $style))) {
            echo 1;
        } else {
            echo 0;
        }
    }

    /**
     * 异步轮询推送消息
     */
    public function getMsg()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }

        $uid = session('uid');
        $msg = S('usermsg' . $uid);

        if ($msg) {
            if ($msg['comment']['status']) {
                $msg['comment']['status'] = 0;
                S('usermsg' . $uid, $msg, 0);
                echo json_encode(array(
                    'status' => 1,
                    'total' => $msg['comment']['total'],
                    'type' => 1
                ));
                exit();
            }

            if ($msg['letter']['status']) {
                $msg['letter']['status'] = 0;
                S('usermsg' . $uid, $msg, 0);
                echo json_encode(array(
                    'status' => 1,
                    'total' => $msg['letter']['total'],
                    'type' => 2
                ));
                exit();
            }

            if ($msg['atme']['status']) {
                $msg['atme']['status'] = 0;
                S('usermsg' . $uid, $msg, 0);
                echo json_encode(array(
                    'status' => 1,
                    'total' => $msg['atme']['total'],
                    'type' => 3
                ));
                exit();
            }
        }
        echo json_encode(array('status' => 0));
    }

    /**
     * 图片上传处理
     * @param  [String] $path   [保存文件夹名称]
     * @param  [String] $width  [缩略图宽度]
     * @param  [String] $height [缩略图高度]
     * @return [Array]         [图片上传信息]
     */
    private function _upload($path, $width, $height)
    {
        $obj = new \Think\Upload();// 实例化上传类
        $obj->maxSize = C('UPLOAD_MAX_SIZE');    //图片最大上传大小
        $obj->savePath = '';    //设置文件上传（子）目录
        $obj->rootPath = C('UPLOAD_PATH') . $path . '/';// 设置文件上传根目录
        $obj->saveRule = 'uniqid';    //保存文件名
        $obj->uploadReplace = true;    //覆盖同名文件
        $obj->allowExts = C('UPLOAD_EXTS');    //允许上传文件的后缀名
        $obj->thumb = true;    //生成缩略图
        $thumbPrefix = 'mini,medium,max';
        $obj->thumbPrefix = $thumbPrefix;//缩略图后缀名
        $obj->autoSub = false;//不使用子目录保存
        $obj->thumbRemoveOrigin = true;    //删除原图
        $fileName = date('YmdHis', time()) . '_' . rand(100, 999);
        $obj->saveName = $fileName;
        $info = $obj->upload();
        if (!$info) {
            return array('status' => 0, 'msg' => $obj->getErrorMsg());
        } else {
            $image = new \Think\Image();
            $w = explode(',', $width);
            $h = explode(',', $height);
            $prefix = explode(',', $thumbPrefix);
            $num = count($prefix);
            $result['status'] = 1;
            for ($i = 0; $i < $num; $i++) {
                $image->open($obj->rootPath . $info['Filedata']['savename']);
                $t = $prefix[$i];
                $image->thumb($w[$i], $h[$i])->save($obj->rootPath . $t . '_' . $info['Filedata']['savename'], 'jpeg', 100, true);
                $p[$t] = $obj->rootPath . $prefix[$i] . '_' . $info['Filedata']['savename'];
            }
            @unlink($obj->rootPath . $info['Filedata']['savename']);
            $result['path'] = $p;
            return $result;
        }
    }
}